//
//  KLMBaseModeSettingController.swift
//  KLM_GN
//
//  Created by Nic on 2025/3/7.
//

import UIKit

enum DeviceModeType {
    case AI // AI模式
    case scene // 情景模式
}

typealias ConfirmConfigBlock = () -> ()

class KLMBaseModeSettingController: KLMBaseController {
    let modeType: DeviceModeType
    private var cachedVcs: [UIViewController] = []
    var configBlcok: ConfirmConfigBlock?
    let rkScene: KLMRKScene
    var isDown: Bool = false // 是否是 下发光
    @IBOutlet weak var containerView: UIView!
    @IBOutlet weak var downBtn: KLMBaseButton!
    @IBOutlet weak var upBtn: KLMBaseButton!
    
    init(type: DeviceModeType, rkScene: KLMRKScene) {
        self.modeType = type
        self.rkScene = rkScene
        super.init(nibName: "KLMBaseModeSettingController", bundle: nil)
    }
    
    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        downBtn.isSelected = true
        isDown = true
        title = titleText
        
        let rightItem = KLMBaseButton()
        navigationItem.rightBarButtonItem = UIBarButtonItem.itemWithBaseButton(rightItem, target: self, action: #selector(confirmConfig(_:)), configBlock: { baseItem in
            baseItem.configStyle(with: KLMLocalizable.LANGLOC("Confirm"), font: UIFont(safeName: "PingFangSC-Regular", size: 18), titleColor: appMainThemeColor)
        })
    }
    // MARK: - 确认
    @objc func confirmConfig(_ sender: KLMBaseButton) {
//        guard let sceneConfig = rkScene.sceneConfig else { return }
        if let vc = cachedVcs[isDown ? 0 : 1] as? KLMModeSettingController {
            let (success, dict) = vc.mergeConfigData()
            if !success {
                KLMAlertController.showAlertWithTitle(title: dict["error"] as? String, message: nil)
                return
            }
            var config = dict
            if let sceneConfig = rkScene.sceneConfig, let configDict = sceneConfig.toDictionary() {
                config = configDict.merging(dict) { _, new in
                    new
                }
            }
            SVProgressHUD.show()
            // 更新场景配置
            KLMRequest.updateSceneConfig(sceneId: rkScene.id, sceneConfig: config) { response in
                SVProgressHUD.showSuccess(withStatus: KLMLocalizable.LANGLOC("Success"))
                
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                    if let configBlcok = self.configBlcok {
                        configBlcok()
                    }
                    self.navigationController?.popViewController(animated: true)
                }
            } failure: { error in
                SVProgressHUD.dismiss()
                KLMHttpShowError(error)
            }
        }
    }
    
    func setupContentView() {
        let downVc = KLMModeSettingController(modeType: modeType, glowType: .down, rkScene: rkScene)
        let upVc = KLMModeSettingController(modeType: modeType, glowType: .up, rkScene: rkScene)
        cachedVcs = [downVc, upVc]
        showChildVc(at: 0)
    }
    
    private func showChildVc(at index: Int) {
        if index >= cachedVcs.count {
            return
        }
        // 移除当前显示的子控制器
        for child in children {
            child.willMove(toParent: nil)
            child.view.removeFromSuperview()
            child.removeFromParent()
        }
        
        // 获取要显示的子控制器
        let childVC = cachedVcs[index]
        
        // 将子控制器添加到当前控制器
        addChild(childVC)
        view.addSubview(childVC.view)
        childVC.view.snp.makeConstraints { make in
            make.top.equalTo(containerView.snp.bottom).offset(22.0)
            make.left.right.bottom.equalToSuperview()
        }
        childVC.didMove(toParent: self)
    }
    
    @IBAction func tapDown(_ sender: KLMBaseButton) {
        if !sender.isSelected {
            sender.isSelected = true
            showChildVc(at: 0)
        }
        if upBtn.isSelected {
            upBtn.isSelected = false
        }
        isDown = true
    }
    
    @IBAction func tapUp(_ sender: KLMBaseButton) {
        if !sender.isSelected {
            sender.isSelected = true
            showChildVc(at: 1)
        }
        if downBtn.isSelected {
            downBtn.isSelected = false
        }
        isDown = false
    }
    override func viewDidLoadConfig() {
        super.viewDidLoadConfig()
        // 设置边框
        containerView.layer.borderWidth = 1
        containerView.layer.cornerRadius = 8
        containerView.layer.masksToBounds = true
        
        downBtn.configStyle(with: "下发光", font: UIFont(safeName: "PingFangSC-Bold", size: 16))
        downBtn.titleLabel?.textAlignment = .center
        upBtn.titleLabel?.textAlignment = .center
        upBtn.configStyle(with: "上发光", font: UIFont(safeName: "PingFangSC-Bold", size: 16))
    }
    override func applyTheme(_ theme: any Theme) {
        super.applyTheme(theme)
        containerView.layer.borderColor = theme.themeColor.cgColor
        
        downBtn.configStyle(titleColor: theme.btnBgColor)
        downBtn.configStyle(titleColor: .white, state: .highlighted)
        downBtn.configStyle(titleColor: theme.btnTextColor, state: .selected)
        downBtn.setBackgroundImage(UIImage(color: theme.btnTextColor), for: .normal)
        downBtn.setBackgroundImage(UIImage(color: theme.btnBgColor), for: .highlighted)
        downBtn.setBackgroundImage(UIImage(color: theme.btnBgColor), for: .selected)
        
        upBtn.configStyle(titleColor: theme.btnBgColor)
        upBtn.configStyle(titleColor: .white, state: .highlighted)
        upBtn.configStyle(titleColor: theme.btnTextColor, state: .selected)
        upBtn.setBackgroundImage(UIImage(color: theme.btnTextColor), for: .normal)
        upBtn.setBackgroundImage(UIImage(color: theme.btnBgColor), for: .highlighted)
        upBtn.setBackgroundImage(UIImage(color: theme.btnBgColor), for: .selected)
        
        setupContentView()
    }
}
